import { login, getUserInfo } from '@/api/sys'
import { getItem, setItem, removeAllItem } from '@/utils/storage'
import { setTimeStamp } from '@/utils/auth'
import { TOKEN } from '@/constant'
import router from '@/router'
const state = {
  token: getItem(TOKEN),
  userInfo: {}
}

const mutations = {
  SET_TOKEN(state, token) {
    console.log(token)
    state.token = token
  },
  SET_USER_INFO(state, userInfo) {
    state.userInfo = userInfo
  }
}

const actions = {
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login({
        username: userInfo.username.trim(),
        password: userInfo.password.trim()
      })
        .then((res) => {
          commit('SET_TOKEN', res.token)
          setItem(TOKEN, res.token)
          // 设置登录的时间戳
          setTimeStamp()
          resolve()
        })
        .catch((err) => {
          reject(err)
        })
    })
  },
  async getUserInfo({ commit }) {
    const res = await getUserInfo()
    commit('SET_USER_INFO', res)
    return res
  },
  logout({ commit }) {
    commit('SET_TOKEN', '')
    commit('SET_USER_INFO', {})
    removeAllItem()
    router.push('/login')
  }
}

const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
